/**
 * @author - lhn
 * @version - 1.0.0
 * @description - 并发相关 hooks
 * @file - useConcurrent.ts
 * @datetime - 2025/2/28
 * @editor - lhn
 */


import { IUseConcurrent } from './IUseConcurrent';

/** 并发 */
class UseConcurrent implements IUseConcurrent {
  constructor() {
  }

  public parallelTask = (tasks: Function[], parallelCount: number): Promise<string> => {
    return new Promise(
      (resolve): void => {
        if (tasks.length === 0) {
          resolve('任务执行完毕，执行数量0');
          return;
        }

        let nextIndex: number = 0;  // 下一个任务的下标
        let finishTaskCount: number = 0;  // 执行任务数量

        // 运行下一个任务
        function _run(): void {
          const task = tasks[nextIndex];
          nextIndex++;

          task().then((): void => {
            finishTaskCount++;
            if (nextIndex < tasks.length) {
              _run();
            } else if (finishTaskCount === tasks.length) {
              resolve(`任务完成，完成数量${finishTaskCount}`);
            }
          });
        }

        for (let i: number = 0; i < tasks.length && i < parallelCount; i++) {
          _run();
        }
      }
    );
  };
}

const useConcurrent = new UseConcurrent();
export default useConcurrent;